package cn.dankal.flyaudio.friend;

import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.util.List;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import api.ChatServiceFactory;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.ReportReq;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.GlideEngine;
import cn.dankal.basiclib.util.SpannableStringUtils;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.ImgAdapter;
import cn.dankal.flyaudio.friend.pickimage.StringUtil;
import cn.dankal.flyaudio.friend.utils.takevideo.utils.LogUtils;
import cn.dankal.flyaudio.oss.view.AliUploadActivity;

public class ReportActivity extends AliUploadActivity {

    private EditText contentView;
    private TextView contentNumView;
    private RecyclerView recyclerView;
    private ImgAdapter mImgAdapter;
    private int imgPosition;
    private TextView tvImgSize;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_report;
    }

    @Override
    protected void initComponents() {
        super.initComponents();
        addSingleTitleBar("举报");
        contentView = findViewById(R.id.et_content);
        contentNumView = findViewById(R.id.tv_num);
        recyclerView = findViewById(R.id.rv_pic);
        tvImgSize = findViewById(R.id.tv_img_size);
        findViewById(R.id.tv_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadingDialog();
                if (mImgAdapter.getDatas().size() != 0) {
                    elements.clear();
                    for (String data : mImgAdapter.getDatas()) {
                        elements.add(Uri.parse(data));
                    }

                    for (String data : mImgAdapter.getDatas()) {
                        String objectName = "fg_" + DKUserManager.getUserInfo().getId() + "_" + System.currentTimeMillis() + ".jpg";
                        finalKeys.add(objectName);
                        mService.asyncPutData(objectName, data);
                    }
                } else {
                    doReport();
                }
            }
        });
        mImgAdapter = new ImgAdapter();
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL,
                false));
        recyclerView.setAdapter(mImgAdapter);
        mImgAdapter.addData("");
        contentView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SpannableStringBuilder num = SpannableStringUtils.getBuilder(s.length() + "").setForegroundColor(Color.parseColor("#0085b4"))
                        .append("/500")
                        .setForegroundColor(Color.parseColor("#4A4A4A"))
                        .create();
                contentNumView.setText(num);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
//        uploadListener = new UploadListener() {
//            @Override
//            public void onSucess(String filepath, String key) {
//                loadingDialog.dismiss();
//                LogUtils.e(imgPosition + "-------" + filepath + "-----" + key);
//                mImgAdapter.addData(PicUtils.getUrl(key));
//                if (mImgAdapter.getDatas().size() < 6) {
//                    if(!StringUtil.isEmpty(mImgAdapter.getDatas().get(mImgAdapter.getDatas().size()-1))) {
//                        mImgAdapter.addData("");
//                    }
//                }
//                setTextSize();
//                mImgAdapter.notifyDataSetChanged();
//            }
//
//            @Override
//            public void onUpload(double percent) {
//                builder.setTipWord(percent + "%").showProgress();
//            }
//
//            @Override
//            public void onError(String string) {
//                ToastUtils.showLong(string);
//                loadingDialog.dismiss();
//                TipDialog dialog = builder.setIconType(TipDialog.Builder.ICON_TYPE_FAIL)
//                        .setTipWord("上传失败")
//                        .create(2000);
//                dialog.show();
//                dialog.dismiss();
//            }
//        };
        LiveEventBus.get("addImg", int.class).observe(this,
                new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        if (StringUtil.isEmpty(mImgAdapter.getDatas().get(integer))) {
                            //添加图片
//                            imgPosition = integer;
//                            AliUIDisplayer aliUIDisplayer =
//                                    new AliUIDisplayer(recyclerView.getChildAt(integer).findViewById(R.id.item_iv_icon),
//                                            ReportActivity.this, uploadListener);
//                            uploadHelper = new AliUploadHelper(ReportActivity.this, aliUIDisplayer);
                            open();
                        }
                    }
                });

        LiveEventBus.get("deleteImg", int.class).observe(this,
                new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        LogUtils.e("deleteImg" + integer);
                        mImgAdapter.getDatas().remove(mImgAdapter.getDatas().get(integer));
                        if (mImgAdapter.getDatas().size() != 0) {
                            if (!StringUtil.isEmpty(mImgAdapter.getDatas().get(mImgAdapter.getDatas().size() - 1))) {
                                mImgAdapter.addData("");
                            }
                        }
                        mImgAdapter.notifyDataSetChanged();
                        setTextSize();
                    }
                });
    }

    private void doReport() {
        String reason = contentView.getText().toString().trim();
        if (TextUtils.isEmpty(reason)) {
            ToastUtils.showShort("请输入举报理由!");
            return;
        }
//        List<String> imgs = new ArrayList<>();
//        imgs.addAll(finalKeys.());
        for (String img : finalKeys) {
            if (TextUtils.isEmpty(img)) {
                finalKeys.remove(img);
            }
        }
        if (finalKeys.isEmpty()) {
            ToastUtils.showShort("请上传图片!");
//            finalKeys.add("");
            return;
        }

        ReportReq req = new ReportReq();
        req.setTargetType(ReportReq.GROUP);
        req.setTargetId(getIntent().getLongExtra(FlyApplication.TARGET_ID, 0) + "");
        req.setReason(reason);
        req.setImgList(finalKeys);
        ChatServiceFactory.reports(req)
                .subscribe(new AbstractSubscriber<BaseResponse<Object>>(this) {
                    @Override
                    public void onNext(BaseResponse<Object> objectBaseResponse) {
                        com.blankj.utilcode.util.ToastUtils.showShort("举报成功");
                        dismissLoadingDialog();
                        finishActivity();
                    }
                });
    }

    private void open() {

        PictureSelector.create(ActivityUtils.getTopActivity())
                .openGallery(PictureMimeType.ofImage())
//                .maxSelectablePerMediaType(6,1)
                .maxSelectNum(maxPosition-selectPosition)
                .loadImageEngine(GlideEngine.Companion.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {

                    @Override
                    public void onResult(List<LocalMedia> result) {
                        finalKeys.clear();
                        // 例如 LocalMedia 里面返回五种path
                        // 1.media.getPath(); 原图path，但在Android Q版本上返回的是content:// Uri类型
                        // 2.media.getCutPath();裁剪后path，需判断media.isCut();切勿直接使用
                        // 3.media.getCompressPath();压缩后path，需判断media.isCompressed();切勿直接使用
                        // 4.media.getOriginalPath()); media.isOriginal());为true时此字段才有值
                        // 5.media.getAndroidQToPath();Android Q版本特有返回的字段，但如果开启了压缩或裁剪还是取裁剪或压缩路
                        // 径；注意：.isAndroidQTransform(false);此字段将返回空
                        // 如果同时开启裁剪和压缩，则取压缩路径为准因为是先裁剪后压缩
                        // TODO 可以通过PictureSelectorExternalUtils.getExifInterface();方法获取一些额外的资源信息，
                        //  如旋转角度、经纬度等信息
                        String url = "";
                        for (LocalMedia media : result) {
                            //Android Q 特有Path:
                            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
//                                upload(new File(media.getAndroidQToPath()));
                                url = media.getAndroidQToPath();
                            } else {
                                if (media.isCompressed()) {
                                    //是否压缩
//                                    upload(new File(media.getCompressPath()));
                                    url = media.getCompressPath();
                                } else {
                                    if (media.isOriginal()) {
                                        //是否开启原图
//                                        upload(new File(media.getOriginalPath()));
                                        url = media.getOriginalPath();
                                    } else {
//                                        upload(new File(media.getPath()));
                                        url = media.getPath();
                                    }
                                }
                            }


                            if (mImgAdapter.getDatas().size() < 7) {
                                mImgAdapter.remove(mImgAdapter.getDatas().size() - 1);
                                mImgAdapter.addData(url);
                                if (mImgAdapter.getDatas().size() < 6) {
                                    if (!StringUtil.isEmpty(mImgAdapter.getDatas().get(mImgAdapter.getDatas().size() - 1))) {
                                        mImgAdapter.addData("");
                                    }
                                }
                            }
                            setTextSize();
                            mImgAdapter.notifyDataSetChanged();
//                            Uri uri = Uri.parse(url);
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }
    private int selectPosition = 0;
    private int maxPosition = 6;
    private void setTextSize() {
        if (mImgAdapter.getDatas().size() < 6) {
            selectPosition = mImgAdapter.getDatas().size() - 1;
            tvImgSize.setText("上传图片（" + (mImgAdapter.getDatas().size() - 1) + "/6）");
        } else {
            if (StringUtil.isEmpty(mImgAdapter.getDatas().get(5))) {
                selectPosition = mImgAdapter.getDatas().size() - 1;
                tvImgSize.setText("上传图片（" + (mImgAdapter.getDatas().size() - 1) + "/6）");
            } else {
                selectPosition = mImgAdapter.getDatas().size();
                tvImgSize.setText("上传图片（" + (mImgAdapter.getDatas().size()) + "/6）");
            }
        }
    }

//    private UploadListener uploadListener;
//    private AliUploadHelper uploadHelper;
//    private TipDialog.Builder builder;


//    private void uploadPic(Uri photoUris) {
//        builder = new TipDialog.Builder(this);
//        loadingDialog = builder
//                .setIconType(TipDialog.Builder.ICON_TYPE_LOADING)
//                .setTipWord("正在上传").create();
//        loadingDialog.show();
//
//        boolean b = UriUtils.getPath(this, photoUris) == null;
//        uploadHelper.uploadPic(uploadListener, b ? photoUris.getPath() : UriUtils.getPath(this, photoUris));
//    }


    @Override
    public void uploadComplete() {
//        super.uploadComplete();
        doReport();
    }
}
